import { defineStore } from "pinia";

export const useThemeStore = defineStore("theme", {
  state: () => ({
    theme: localStorage.getItem("theme") || "light",
  }),

  getters: {
    isDark: (state) => state.theme === "dark",
  },

  actions: {
    // 初始化主题
    initTheme() {
      const savedTheme = localStorage.getItem("theme");
      const prefersDark = window.matchMedia(
        "(prefers-color-scheme: dark)",
      ).matches;
      this.theme = savedTheme || (prefersDark ? "dark" : "light");
      this.applyTheme();
    },

    // 切换主题
    toggleTheme() {
      this.theme = this.theme === "dark" ? "light" : "dark";
      this.applyTheme();
    },

    // 应用主题
    applyTheme() {
      // 保存到 localStorage
      localStorage.setItem("theme", this.theme);

      // 设置 HTML 属性
      document.documentElement.setAttribute("data-theme", this.theme);

      // 设置系统主题色
      document.documentElement.style.colorScheme = this.theme;

      // 处理 Element Plus 的深色模式
      document.documentElement.classList.toggle("dark", this.theme === "dark");
      document.body.classList.toggle("dark", this.theme === "dark");

      // 处理 Arco Design 的深色模式
      document.body.setAttribute("arco-theme", this.theme);

      // 触发自定义事件，通知所有组件主题已更改
      window.dispatchEvent(
        new CustomEvent("themechange", {
          detail: { theme: this.theme },
        }),
      );

      // 触发一个DOM事件，以便Vue组件可以监听到主题变化
      document.dispatchEvent(
        new CustomEvent("theme-changed", {
          detail: { theme: this.theme, isDark: this.theme === "dark" },
        }),
      );
    },

    // 设置指定主题
    setTheme(theme) {
      if (theme !== "dark" && theme !== "light") return;
      this.theme = theme;
      this.applyTheme();
    },

    // 监听系统主题变化
    watchSystemTheme() {
      const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
      const handleChange = (e) => {
        if (!localStorage.getItem("theme")) {
          this.theme = e.matches ? "dark" : "light";
          this.applyTheme();
        }
      };
      mediaQuery.addEventListener("change", handleChange);
    },
  },
});
